package com.heisen.base.handler;

import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.heisen.base.entity.Api;
import com.heisen.base.exception.AuthException;
import com.heisen.base.exception.RRException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.file.AccessDeniedException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author sen
 * @description
 * @date 2023/12/18 10:52
 */
@Slf4j
public class BaseExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public Api handleException(Exception e) {
        log.error("系统内部异常，异常信息", e);
        return Api.fail("系统内部异常");
    }

    @ExceptionHandler(value = RuntimeException.class)
    public Api handleException(RuntimeException e) {
        log.error("系统运行异常，异常信息", e);
        return Api.fail("系统运行异常");
    }



    @ExceptionHandler(value = AuthException.class)
    public Api handleAuthException(AuthException e) {
        log.error("权限认证错误", e);
        return Api.fail(e.getMessage());
    }

    @ExceptionHandler(value = RRException.class)
    public Api handleRRException(RRException e) {
        log.error("系统错误", e);
        return Api.fail(e.getMessage());
    }

    @ExceptionHandler(value = AccessDeniedException.class)
    public Api handleAccessDeniedException(){
        return Api.fail("没有权限访问该资源");
    }


    /**
     * 统一处理请求参数校验(普通传参)
     *
     * @param e ConstraintViolationException
     * @return Api
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    public Api handleConstraintViolationException(ConstraintViolationException e) {
        StringBuilder message = new StringBuilder();
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        for (ConstraintViolation<?> violation : violations) {
            Path path = violation.getPropertyPath();
            String[] pathArr = StringUtils.splitByWholeSeparatorPreserveAllTokens(path.toString(), ".");
            message.append(pathArr[1]).append(violation.getMessage()).append(",");
        }
        message = new StringBuilder(message.substring(0, message.length() - 1));
        return Api.fail(message.toString());
    }

    //处理请求参数格式错误 @RequestBody上validate失败后抛出的异常是MethodArgumentNotValidException异常。
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Api MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.info("【MethodArgumentNotValidException 异常】");
        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(","));
        return Api.fail(message);
    }


    /**
     * 统一处理请求参数校验(实体对象传参)
     *
     * @param e BindException
     * @return Api
     */
    @ExceptionHandler(BindException.class)
    public Api handleBindException(BindException e) {
        StringBuilder message = new StringBuilder();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for (FieldError error : fieldErrors) {
            message.append(error.getField()).append(error.getDefaultMessage()).append(",");
        }
        message = new StringBuilder(message.substring(0, message.length() - 1));
        return Api.fail(message.toString());
    }



    public  String getUserMessage(InvalidFormatException rootCause) {
        // 目标类型
        Class<?> targetType = rootCause.getTargetType();
        // 目标类型提示信息
        String targetTypeNotification = "";
        if (targetType == BigInteger.class || targetType == Integer.class || targetType == Long.class
                || targetType == Short.class || targetType == Byte.class) {
            targetTypeNotification = "参数类型应为：整数；";
        } else if (targetType == BigDecimal.class || targetType == Double.class || targetType == Float.class) {
            targetTypeNotification = "参数类型应为：数值；";
        } else if (targetType == Boolean.class ){
            targetTypeNotification = "参数类型应为：布尔；";
        } else if(targetType.isEnum()){
            targetTypeNotification ="参数类型应为：固定枚举值；";
        }
        String fieldName = rootCause.getPath().get(0).getFieldName();
        Object value = rootCause.getValue();

        return String.format("参数格式错误！[%s] 当前参数名为[%s] 当前输入参数值为：[%s]", targetTypeNotification,fieldName, value);
    }
}
